/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Inventario.java
 *
 * Created on Jul 27, 2011, 11:31:26 AM
 */

package dced.ui;
import java.awt.event.WindowListener;
import dced.entity.Inventario;
import dced.util.HibernateUtil;
//import java.math.BigDecimal;
import java.util.*;
import javax.swing.table.DefaultTableModel;
import org.hibernate.*;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import java.io.*;
import javax.swing.filechooser.*;
import javax.swing.JFileChooser;
/**
 *
 * @author antonio
 */
public class V_Inventario extends javax.swing.JFrame {

    /** Creates new form Inventario */
    public V_Inventario() {
        initComponents();
        V_Inventario.this.actualizarActionPerformed(null);
    }
    
    private static String QUERY_ALL="from Inventario";
    
    private void displayResult(java.util.List resultList) {
    Vector<String> tableHeaders = new Vector<String>();
    Vector tableData = new Vector();
    tableHeaders.add("Cantidad"); 
    tableHeaders.add("Descripción");
    tableHeaders.add("Precio");
    tableHeaders.add("Clave");

    for(Object o : resultList) {
        Inventario inventario = (Inventario)o;
        Vector<Object> oneRow = new Vector<Object>();
        oneRow.add(inventario.getCantidadInventario());
        oneRow.add(inventario.getDescripcionInventario());
        oneRow.add(inventario.getPrecioUnitarioInventario());
        oneRow.add(inventario.getClaveInventario());
        tableData.add(oneRow);
    }
    jTable1.setModel(new DefaultTableModel(tableData, tableHeaders));
}
    
    
    

    private void runQueryAll(String hql) {
        try {
        Session session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();
        Query q = session.createQuery(hql);
        java.util.List resultList = q.list();
        displayResult(resultList);
        session.getTransaction().commit();
    } catch (HibernateException he) {
        he.printStackTrace();
    }
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        OK = new java.awt.Button();
        jTextField1 = new javax.swing.JTextField();
        jTextField2 = new javax.swing.JTextField();
        jTextField3 = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();
        jLabel5 = new javax.swing.JLabel();
        jTextField4 = new javax.swing.JTextField();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jToggleButton1 = new javax.swing.JToggleButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        OK.setActionCommand("Agregar_Item");
        OK.setLabel("Actualizar");
        OK.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                actualizarActionPerformed(evt);
            }
        });

        jLabel1.setText("Cantidad");

        jLabel2.setText("Precio");

        jLabel3.setText("Descripción");

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);

        jButton1.setText("Insertar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                Insertar_Art(evt);
            }
        });

        jLabel5.setText("ID");

        jButton2.setText("Modificar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                modificarActionPerformed(evt);
            }
        });

        jButton3.setText("Borrar");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                borrarActionPerformed(evt);
            }
        });

        jToggleButton1.setText("Generar reporte");
        jToggleButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jToggleButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel3)
                            .addComponent(jLabel2)
                            .addComponent(jLabel1))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jTextField1)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jTextField2, javax.swing.GroupLayout.DEFAULT_SIZE, 106, Short.MAX_VALUE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
                            .addComponent(jTextField3)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(103, 103, 103)
                        .addComponent(jButton1)))
                .addGap(27, 27, 27)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jToggleButton1)
                        .addGap(51, 51, 51)
                        .addComponent(OK, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jButton3)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jButton2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 518, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(52, 52, 52)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jLabel1))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jLabel2))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(jLabel3)
                                    .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(jButton1)
                                    .addComponent(jToggleButton1)))
                            .addComponent(OK, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(55, 55, 55)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel5)
                            .addComponent(jButton2)
                            .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton3)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 369, Short.MAX_VALUE)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(24, 24, 24))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void actualizarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_actualizarActionPerformed
        // TODO add your handling code here:
        //Inventario inv=new Inventario();
        runQueryAll(QUERY_ALL);
  

    }//GEN-LAST:event_actualizarActionPerformed

    private void Insertar_Art(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Insertar_Art
        // TODO add your handling code here:
        Inventario inv=new Inventario();
        inv.setCantidadInventario(Short.parseShort(jTextField2.getText()));
        inv.setDescripcionInventario(jTextField3.getText());
        inv.setPrecioUnitarioInventario(Float.parseFloat(jTextField1.getText()));
        
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = session.beginTransaction();
   
        session.save(inv);
        session.flush();
        session.clear();
        
        tx.commit();
        session.close();
        V_Inventario.this.actualizarActionPerformed(evt);
    }//GEN-LAST:event_Insertar_Art

    private void modificarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_modificarActionPerformed
        // TODO add your handling code here:
        Inventario inv=new Inventario();
        inv.setCantidadInventario(Short.parseShort(jTextField2.getText()));
        inv.setDescripcionInventario(jTextField3.getText());
        inv.setPrecioUnitarioInventario(Float.parseFloat(jTextField1.getText()));
        inv.setClaveInventario(Integer.parseInt(jTextField4.getText()));
        
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = session.beginTransaction();
   
        session.saveOrUpdate(inv);
        
        session.flush();
        session.clear();
        
        tx.commit();
        session.close();
        V_Inventario.this.actualizarActionPerformed(evt);
    }//GEN-LAST:event_modificarActionPerformed

    private void borrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_borrarActionPerformed
        // TODO add your handling code here:
        Inventario inv=new Inventario();
        inv.setCantidadInventario(Short.parseShort("1"));
        inv.setDescripcionInventario("algo");
        inv.setPrecioUnitarioInventario(Float.parseFloat("1"));
        inv.setClaveInventario(Integer.parseInt(jTextField4.getText()));
        
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = session.beginTransaction();
   
        session.delete(inv);
        
        session.flush();
        session.clear();
        
        tx.commit();
        session.close();
        V_Inventario.this.actualizarActionPerformed(evt);
    }//GEN-LAST:event_borrarActionPerformed

    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
        // TODO add your handling code here:
        jTextField2.setText(String.valueOf(jTable1.getValueAt(jTable1.getSelectedRow(), 0))); //cantidad
        jTextField3.setText((String)jTable1.getValueAt(jTable1.getSelectedRow(), 1)); //descripción
        jTextField1.setText(String.valueOf(jTable1.getValueAt(jTable1.getSelectedRow(), 2)));
        jTextField4.setText(String.valueOf(jTable1.getValueAt(jTable1.getSelectedRow(), 3))); //clave
    }//GEN-LAST:event_jTable1MouseClicked

    private void jToggleButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jToggleButton1ActionPerformed
        
        JFileChooser fc = new JFileChooser();
        FileNameExtensionFilter filter = new FileNameExtensionFilter("PDF", "pdf", "PDF");
        fc.setFileFilter(filter);
        int returnVal = fc.showSaveDialog(this);

            if (returnVal == JFileChooser.APPROVE_OPTION) {
                java.io.File file = fc.getSelectedFile();
                //This is where a real application would save the file.

                String ruta = file.getPath();
                ruta = (ruta.toLowerCase().endsWith(".pdf")) ? ruta : (ruta + ".pdf");
                
        Document document = new Document(PageSize.A4);
        try{
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(ruta));
            writer.setPdfVersion(PdfWriter.VERSION_1_6);
            document.addTitle("Reporte_Inventario");
             document.open();
             Image foto = Image.getInstance("/home/kreuz_katze/Imágenes/DCED_logo.png");
                        foto.scaleToFit(500, 500);
                        foto.setAlignment(Chunk.ALIGN_CENTER);
                        document.add(foto);
             Paragraph par = new Paragraph("Reporte de articulos en el Inventario",FontFactory.getFont("arial", 14, BaseColor.BLACK));
            par.setIndentationLeft(par.ALIGN_JUSTIFIED_ALL);
            par.setAlignment(par.TITLE);
            par.getExtraParagraphSpace();
            
            int columnas = jTable1.getColumnCount();
            int filas = jTable1.getRowCount();
            
            String numCadena[]=new String[300];
                    int y=0;

                    for(int n=0;n<filas;n++)
                    {
                      for(int m=0;m<columnas;m++)
                      {
                        numCadena[y]= String.valueOf(jTable1.getValueAt(n,m));
                        y++;
                      }
                    }
                    
                    String enc[]=new String[10];
                      for(int m=0;m<columnas;m++)
                     {
                       enc[m]=String.valueOf(jTable1.getColumnModel().getColumn(m).getHeaderValue());
                     }

                    PdfPTable tabla=new PdfPTable (columnas);
                    
                    for(int i=0;i<columnas;i++)
                    {
                      tabla.addCell(new Paragraph(enc[i],FontFactory.getFont("arial",8,BaseColor.BLACK)));

                    }
                    
                    int total=columnas*filas;


                     for(int i=0;i<total;i++)
                     {
                      tabla.addCell(new Paragraph(numCadena[i],FontFactory.getFont("arial",6,BaseColor.DARK_GRAY)));
                     }
                     
              
                     document.add(par);
                     document.add(new Paragraph("  "));
                     document.add(new Paragraph("  "));
                     document.add(tabla);
                     document.close();
                    
        } catch(Exception e){
            e.printStackTrace();
        }
            }   
    }//GEN-LAST:event_jToggleButton1ActionPerformed

   
    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new V_Inventario().setVisible(true);
            }
        });
       
        
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private java.awt.Button OK;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextField3;
    private javax.swing.JTextField jTextField4;
    private javax.swing.JToggleButton jToggleButton1;
    // End of variables declaration//GEN-END:variables

}
